package cn.gcjlearn.websocketdemo.websockethandler;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Component
@ServerEndpoint("/test")
public class TestWebSocket {

    @OnOpen
    public void open(Session session) throws IOException {
        System.out.println("环境连接");
        sendMsg(session);
    }

    @OnMessage
    public void message(Session session, String msg) throws IOException {
    }

    @OnClose
    public void close(Session session) {
    }

    private void sendMsg(Session session) {
        while (true) {
            try {
                session.getBasicRemote().sendText("欢迎进入聊天室：" + Math.random());
                Thread.sleep(1000L);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
